using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Messaging;
using SMS.SportAutoService.Model;
using SMS.SportAutoService.BLL;
using SMS.SportAutoService;
using System.Collections;

[WebService(Namespace = "http://210.245.87.31:2550/Service.asmx/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    static DataControler dc = new DataControler();
    private string connectionString = "";
    public const int userId = 1;
    public const int league_level = 1;

    public Service()
    {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod(Description = "Invoke this method to send your MT auto to our databases. Return string messageId if success; -1 if failure;0 if doesn't exist messageId or not update successfull \nTham so: int commandServiceId, string leagueHomeAwayCode:Ma giai$Ma doi chu nha$Ma Doi khach, string mainExpandCode: Ma Chinh$Ma mo rong, string messageContents: -1(messageId)$0(1-Da ket thuc)$Content1$Content2$...$contentn")
            ]
    public string ReceiverMTAutoString(int commandServiceId, string leagueHomeAwayCode, string mainExpandCode, string messageContents)
    {
        String result = commandServiceId.ToString();


        //MOReceiverDAL.insertMO(userId, Convert.ToInt32(serviceId), commandCode, message, requestId, DateTime.Now);
        MOReceiver mo =
            new MOReceiver(0, commandServiceId, leagueHomeAwayCode, mainExpandCode, messageContents, DateTime.Now);
        result = sendMO(mo);

        //result = "-1";

        return result;
    }

    /*[WebMethod(Description = "Invoke this method to send your MO to our system. Return commandServiceCodeId if success; 0 if failure \nTham so: int commandServiceId, string leagueHomeAwayCode:Ma giai$Ma doi chu nha$Ma Doi khach, string mainExpandCode: Ma Chinh$Ma mo rong, string messageContents: Content1$Content2$...$contentn")]
   /* public int ReceiverMTAutoInt(int commandServiceId, string leagueHomeAwayCode, string mainExpandCode, string messageContents)
    {
        int result = commandServiceId;

        try
        {
            //MOReceiverDAL.insertMO(userId, Convert.ToInt32(serviceId), commandCode, message, requestId, DateTime.Now);
            MOReceiver mo =
                new MOReceiver(0, commandServiceId, leagueHomeAwayCode, mainExpandCode, messageContents, DateTime.Now);
            sendMO(mo);
        }
        catch (Exception e)
        {
            result = 0;
        }

        return result;
    }
*/

    public static string sendMO(MOReceiver mo)
    {
        string result = "-1";
        int messageId = -1;
        //try
        //{

        #region PreProcess


        #endregion

        //Main Processing MO 
        //Chuan bi cho mot CreateMessage
        //idCreated = this.dc.createMessage(idCommandService, leagueCode, homeCode, awayCode, homeCode, codeExpand, leagueLevel, userId);
        string leagueCode = "";
        string homeCode = "";
        string awayCode = "";
        string mainCode = "";
        string codeExpand = "";
        //int leagueLevel,userId;                

        int commandServiceId = mo.CommandServiceId;
        string LAHcode = mo.LeagueHomeAwayCode;
        string MEcode = mo.MainExpandCode;
        string MessageContents = mo.MessageContents;
        DateTime receiverDate = mo.ReceiverDate;

        int max_content = dc.getMaxContent(commandServiceId);
        int league_code_option = dc.getCommandServiceOption(commandServiceId, 1);
        int team_code_option = dc.getCommandServiceOption(commandServiceId, 2);

        StringTokenizer tokens = new StringTokenizer(LAHcode, "$");
        if (league_code_option == 1)
        {
            if (LAHcode == "")
            {
                //Console.WriteLine("MT nhap vao ko dung dinh dang. Tin nhan nay yeu cau Ma giai");
            }
            else
            {
                //tokens = new StringTokenizer(LAHcode, "$");
                leagueCode = tokens.NextToken();
            }
        }

        if (team_code_option == 1)
        {

            if (tokens.HasMoreTokens())
            {
                homeCode = tokens.NextToken();
            }
            if (tokens.HasMoreTokens())
            {
                awayCode = tokens.NextToken();
            }
        }
        else { homeCode = ""; awayCode = ""; }

        if (MEcode != "")
        {
            tokens.NewSource(MEcode);
            mainCode = (tokens.HasMoreTokens()) ? tokens.NextToken() : "";
            codeExpand = (tokens.HasMoreTokens()) ? tokens.NextToken() : "";
        }

        //De xac dinh la update hay insert message
        tokens.NewSource(MessageContents);
        // Lay messageId de cho su kien insert hay update
        string service_number = tokens.NextToken();
        string messId = tokens.NextToken();
        string messEnd = tokens.NextToken();//xac dinh trang thai ket thuc hay chua cho tin nhan cho. =1 la ket thuc, 0 la chua.
        messageId = Convert.ToInt32(messId);
        int countUpdate = 0;
        int countCreate = 0;

        if (messId == "-1")//tao moi mot message
        {
            messageId = dc.createMessage(commandServiceId, service_number, leagueCode, homeCode, awayCode, homeCode, codeExpand, league_level, userId);
        }
        else // 
        {
            //kiem tra xem messageId do co ton tai trong CSDL ko?
            ArrayList alMessage = dc.getMessageByMessageId(messageId);
            ArrayList contentList = dc.getContentList(messageId);
            string strtemp = "";
            //Kiem tra xem tin nhan do da co co ket thuc chua?

            if ((alMessage == null) || (alMessage.Count == 0) || (dc.checkCloseMessage(messageId) == 1))
            {
                //ko co messageID nay 
                //hoac message da ket thuc
                int messageType = dc.getMessageType(commandServiceId);
                if (messageType == 2)
                {
                    messageId = 0;
                }
            }

            if (messageId != 0)
            {
                messageId = Convert.ToInt32(messId);
                ArrayList alContent = dc.getContentList(messageId);
                //Lay tung MT cua content gui toi
                int numberMessageCurrent = dc.getContentNumberFromMessage(messageId);
                int nowContentNumber = numberMessageCurrent;
                if (max_content > tokens.CountTokens() - 3)
                {
                    for (int i = 1; i <= tokens.CountTokens() - 3; i++)
                    {

                        if (i > alContent.Count)//Neu i o vi tri lon hon so luong MT hien tai, thi tao moi
                        {
                            nowContentNumber++;
                            strtemp = tokens.NextToken();
                            if (strtemp.Length > 160) { strtemp = strtemp.Substring(0, 160); }
                            dc.createMessageContent(messageId, nowContentNumber, strtemp, userId);
                            closeMessage(messageId, commandServiceId);
                            countCreate++;
                        }
                        else
                        {
                            strtemp = tokens.NextToken();
                            if (strtemp.Length > 160) { strtemp = strtemp.Substring(0, 160); }
                            dc.updateContentMessage(((ContentObject)contentList[i - 1]).id, messageId, strtemp, userId);
                            countUpdate++;
                        }
                    }
                }
                else
                {
                    for (int i = 1; i <= max_content; i++)
                    {
                        if (i > alContent.Count)//Neu i o vi tri lon hon so luong MT hien tai, thi tao moi
                        {
                            nowContentNumber++;
                            strtemp = tokens.NextToken();
                            if (strtemp.Length > 160) { strtemp = strtemp.Substring(0, 160); }
                            dc.createMessageContent(messageId, nowContentNumber, strtemp, userId);
                            closeMessage(messageId, commandServiceId);
                            countCreate++;
                        }
                        else
                        {
                            strtemp = tokens.NextToken();
                            if (strtemp.Length > 160) { strtemp = strtemp.Substring(0, 160); }
                            dc.updateContentMessage(((ContentObject)contentList[i - 1]).id, messageId, strtemp, userId);
                            countUpdate++;
                        }
                    }
                }

                if (countUpdate != 0)
                {
                    int nowUpdate = dc.getCounter(messageId) + 1;
                    dc.updateCount(nowUpdate, messageId);
                    if (countUpdate < numberMessageCurrent)
                    {
                        for (int i = countUpdate; i < numberMessageCurrent; i++)
                        {
                            dc.updateContentMessage(((ContentObject)contentList[i]).id, messageId, "", userId);
                        }
                    }
                }
            }
        }

        //Console.WriteLine("commandServiceId: " + commandServiceId + " leagueCode: " + leagueCode + "  homeCode: " + homeCode + "  awayCode: " + awayCode + " maindCode: " + mainCode + " codeExpand: " + codeExpand + " league_level: " + league_level + " userId: " + userId);

        string temp;
        if (messId == "-1")
        {
            if (max_content < tokens.CountTokens() - 3)
            {
                //Console.WriteLine("So message contents vuot qua so MT cho 1 message. Chuong trinh se tu dong cat MT cuoi :(");

                for (int i = 1; i <= max_content; i++)
                {
                    if (tokens.HasMoreTokens())
                    {
                        temp = tokens.NextToken();
                        if (temp.Length > 160) { temp = temp.Substring(0, 160); }
                        dc.createMessageContent(messageId, i, temp, userId);
                        //Console.WriteLine("MT" + i.ToString() + ": " + temp);
                    }
                }
            }
            else
            {
                for (int i = 1; i < tokens.CountTokens() - 2; i++)
                {
                    temp = tokens.NextToken();
                    if (temp.Length > 160) { temp = temp.Substring(0, 160); }
                    dc.createMessageContent(messageId, i, temp, userId);
                    // Console.WriteLine("MT" + i.ToString() + ": " + temp);
                }
            }

            closeMessage(messageId, commandServiceId);
        }
        else { }//Console.WriteLine("Khong tao duoc content do messageID ko hop le"); }

        if (messEnd == "1")//de ket thuc tin nhan cho
        {
            int contentClose = dc.getContentNumberFromMessage(messageId);
            dc.closeMessage(messageId, contentClose);
        }
        result = messageId.ToString();

        //}
        //catch (Exception e)
        //{
        //    Console.WriteLine(e.Message);
        //}
        result = messageId.ToString();
        return result;
    }

    static protected void closeMessage(int idMessage, int idCommandService)
    {
        int maxContent = dc.getMaxContent(idCommandService);
        int numberCurrentContent = dc.getContentNumberFromMessage(idMessage);
        int idContentMessage = 0;
        if (maxContent == numberCurrentContent)
        {
            idContentMessage = dc.getIdContentMaxFromMessage(idMessage);
            dc.closeMessage(idMessage, maxContent);

        }
    }
}
